package com.zsr.example.config.filter;

import com.zsr.example.config.exception.CommonJsonException;
import com.zsr.example.service.RedisService;
import com.zsr.example.util.IPUtil;
import com.zsr.example.util.JwtUtil;
import com.zsr.example.util.constants.ErrorEnum;
import com.zsr.example.util.constants.RedisKeyConstants;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 前台单点登录 将用户token写入redis覆盖掉，如果用旧的token访问跑出异常
 *
 * @author zhousiren
 * @date 2022/2/25 13:50
 */
@Aspect
@Component
@Slf4j
@Order(4)
public class SsoFilter {

    @Autowired
    private RedisService redisService;

    @Pointcut("execution(public * com.zsr.example.controller.front..*.*(..))")
    public void sso() {
    }

    @Before("sso()")
    public void doBefore() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String memId = JwtUtil.getMemberIdByJwtToken(request);
        if (!StringUtils.isEmpty(memId)) {
            String oldToken = redisService.opsForValueGet(RedisKeyConstants.SSO_LOGIN_KEY + memId);
            if (!request.getHeader(JwtUtil.HEADER_KEY).equals(oldToken))
                throw new CommonJsonException(ErrorEnum.E_20012);
        }
    }
}
